<template>
  <div class="register clearfix">
    <div class="register-wrap">
      <el-row type="flex" justify="center">
        <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="80px">
          <h3>注册</h3>
          <hr>
          <el-steps :active="active" finish-status="success" align-center>
            <el-step title="基本信息填写">
            </el-step>
            <el-step title="学生证上传"></el-step>
            <el-step title="人脸上传"></el-step>
          </el-steps>
          <div v-if="active==0">
            <el-form-item prop="username" label="用户账号">
              <el-input v-model="ruleForm.username" placeholder="请输入用户账号" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="name" label="用户姓名">
              <el-input v-model="ruleForm.name" placeholder="请输入用户姓名" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input v-model="ruleForm.email" placeholder="请输入邮箱" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="设置密码">
              <el-input v-model="ruleForm.password" show-password placeholder="请输入密码" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="checkpassword" label="确认密码">
              <el-input v-model="ruleForm.checkpassword" show-password placeholder="请再次输入密码"
                        autocomplete="off"></el-input>
            </el-form-item>
            <el-button style="margin-top: 12px;" @click="check('ruleForm')">下一步</el-button>
            <br><br>
            <a href="/" style="text-decoration: none;color: black"><u>已有账号? 快去登录吧</u></a>
          </div>
          <div v-if="active==1">
            <br>
            <el-form-item label="学生证" prop="headImg">
              <el-upload
                  class="upload-demo"
                  ref="upload"
                  action="#"
                  :on-remove="handleRemove"
                  :file-list="fileList"
                  :limit="1"
                  :on-change="fail"
                  :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-button style="margin-top: 12px;" @click="front">上一步</el-button>
            <el-button style="margin-top: 12px;" @click="next">下一步</el-button>
          </div>
          <div v-if="active==2">
            <p>
              <el-button
                  @click="onTake"
                  icon="el-icon-camera"
                  size="small">
                拍照上传
              </el-button>
            </p>
            <br>
            <el-button style="margin-top: 12px;" @click="front">上一步</el-button>
            <el-button type="primary" icon @click="doRegister()">完成注册</el-button>
          </div>
        </el-form>
      </el-row>
    </div>
    <el-dialog title="人脸上传" :visible.sync="camera">
      <div>
        <!--canvas截取流-->
        <video ref="video" width="200" height="200" autoplay></video>
        <!--图片展示-->&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <canvas ref="canvas" width="400" height="400"></canvas>
        <!--确认-->
        <br><br>
        <!--开启摄像头-->
        <el-button type="primary" @click="callCamera">开启摄像头</el-button>
        <el-button type="primary" @click="closeCamera">关闭摄像头</el-button>
        <el-button type="primary" @click="photograph">拍照</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {register} from '../api/index';
export default {
  data() {
    var checkusername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('账号不能为空'));
      } else if (value.length < 8) {
        callback(new Error('账号太短啦'));
      }
      callback();
    };
    var password = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (value.length < 1) {
        callback(new Error('您设置的密码位数不符合要求，请大于9位'));
      } else {
        if (this.ruleForm.checkpassword !== '') {
          this.$refs.ruleForm.validateField('checkpassword');
        }
        callback();
      }
    };
    var checkpassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var name = (rule, value, callback) =>{
      if(value===''){
        callback(new Error('请填写姓名'));
      }
      callback();
    };
    var checkemail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请填写邮箱'));
      } else {
        if (value !== '') {
          var reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
          if (!reg.test(value)) {
            callback(new Error('请输入有效的邮箱'));
          }
        }
        callback();
      }
    };
    return {
      active: 0,
      camera: false,
      fileList: [],
      filephoto:[],
      ruleForm: {
        username: '',
        name:'',
        password: '',
        checkpassword: '',
        email: '',
      },
      rules: {
        password: [
          {validator: password, trigger: 'blur'}
        ],
        checkpassword: [
          {validator: checkpassword, trigger: 'blur'}
        ],
        username: [
          {validator: checkusername, trigger: 'blur'}
        ],
        email: [
          {validator: checkemail, trigger: 'blur'}
        ],
        name: [
          {validator: name, trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.closeCamera();
  },
  methods: {
    next() {
      if(this.fileList.length!=0){
        this.active++;
      }else {
        this.$message({
          type: 'warning',
          message: '未上传学生证'
        })
      }
    },
    front() {
      this.active--;
    },
    onTake() {
      this.camera = true;
    },
    check(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.active++
        } else {
          return false;
        }
      });
    },
    handleRemove(file, fileList) {
      this.fileList.pop(file)
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    fail(file, fileList) {
      this.fileList.push(file)
      console.log(file, fileList);
    },
    // 调用摄像头
    callCamera() {      // H5调用电脑摄像头API
      navigator.mediaDevices.getUserMedia({
        video: true
      }).then(success => {        // 摄像头开启成功
        this.$refs['video'].srcObject = success        // 实时拍照效果
        this.$refs['video'].play()
      }).catch(error => {
        console.log(error)
        console.error('摄像头开启失败，请检查摄像头是否可用！')
      })
    },    // 拍照
    photograph(file) {
      let ctx = this.$refs['canvas'].getContext('2d')      // 把当前视频帧内容渲染到canvas上
      ctx.drawImage(this.$refs['video'], 0, 0, 500, 480)      // 转base64格式、图片格式转换、图片质量压缩
      let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7)          // 由字节转换为KB 判断大小
      // let str = imgBase64.replace('data:image/jpeg;base64,', '')
      // let strLength = str.length
      // let fileLength = parseInt(strLength - (strLength / 8) * 2)    // 图片尺寸  用于判断
      // let size = (fileLength / 1024).toFixed(2)
      // console.log(size)     // 上传拍照信息  调用接口上传图片 .........      // 保存到本地
      this.filephoto.pop(file)
      this.filephoto.push(this.base64ToFile(imgBase64))
      // let ADOM = document.createElement('a')
      // ADOM.href = imgBase64
      // ADOM.download = new Date().getTime() + '.jpeg'
      // ADOM.click()
    },
    // 关闭摄像头
    closeCamera() {
      if (!this.$refs['video'].srcObject) {
        this.camera = false
        return
      }
      let stream = this.$refs['video'].srcObject
      let tracks = stream.getTracks()
      tracks.forEach(track => {
        track.stop()
      })
      this.$refs['video'].srcObject = null
    },
    doRegister() {
      console.log(this.fileList)
      if(this.filephoto.length===0){
        this.$message({
          type: 'warning',
          message: '未上传人脸'
        })
      }else {
        let datafile=new FormData();
        // datafile.append("id",this.ruleForm.username)
        // datafile.append("name",this.ruleForm.name)
        datafile.append("sex",0)
        // datafile.append("pwd",this.ruleForm.password)
        // datafile.append("email",this.ruleForm.email)
        // datafile.append("stcard",this.fileList[0].raw)
        // datafile.append("face",this.filephoto[0])
        datafile.append("role",0)
        datafile.append("used",0)
        datafile.append("phone",'123')
        console.log(datafile)
        register(datafile)
            .then(res=>{
              console.log(this.filephoto[0])
          console.log(res)
        })
      }
      this.closeCamera()
      console.log(this.filephoto)
    },
    base64ToFile(urlData) {
      let arr = urlData.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bytes = atob(arr[1]); // 解码base64
      let n = bytes.length
      let ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      console.log([ia])
      return new File([ia], new Date().getTime(), { type: mime });
    },
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.register {
  width: 100%;
  height: 100%;
  background: url("../../src/static/1.png") no-repeat;
  background-size: cover;
  overflow: hidden;
}

.register-wrap {
  background: url("../../src/static/1.png") no-repeat;
  background-size: cover;
  width: 500px;
  height: 557px;
  margin: 215px auto;
  overflow: hidden;
  padding-top: 10px;
  line-height: 20px;
}

h3 {
  color: #0babeab8;
  font-size: 24px;
}

hr {
  background-color: #444;
  margin: 20px auto;
}

form {
  width: 300px;
}
</style>

